//
//  AouthViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/14.
//

import UIKit
import WebKit

/// 授权控制器
class AouthViewController: UIViewController {

    // 调用码云授权url的webview
    var aouthWebView:WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
}

// MARK: - 设置界面
extension AouthViewController {
    
    // 添加webview 到view中 并且还在授权信息
    func setupUI() -> Void {
        
        var config = WKWebViewConfiguration()
        aouthWebView = WKWebView(frame: view.bounds, configuration: config)
        view.addSubview(aouthWebView)
        
        let requestUrl = URLRequest(url: URL(string: URLs.AOUTHURL)!)
        aouthWebView.load(requestUrl)
        aouthWebView.navigationDelegate = self
        
    }
}

// MARK: - 设置代理 监听授权信息
extension AouthViewController: WKNavigationDelegate {
    
    
    // 监听网页加载进度
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            
//            self.progressView.progress = Float(self.wkWebView.estimatedProgress)
        }
        
        // 页面开始加载时调用
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
//            Log4jMessage(message: "开始加载...")
        }
        
        // 当内容开始返回时调用
        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
//            Log4jMessage(message: "当内容开始返回...")
        }
        
        // 页面加载完成之后调用
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
//            Log4jMessage(message: "页面加载完成...")
            /// 获取网页title
//            self.title = self.wkWebView.title
            
//            UIView.animate(withDuration: 0.5) {
//                self.progressView.isHidden = true
//            }
        }
    
    // 页面加载失败时调用
       func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
//           Log4jMessage(message: "页面加载失败...")
//           UIView.animate(withDuration: 0.5) {
//               self.progressView.progress = 0.0
//               self.progressView.isHidden = true
//           }
//           /// 弹出提示框点击确定返回
//           let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
//           let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
//               _=self.navigationController?.popViewController(animated: true)
//           }
//           alertView.addAction(okAction)
//           self.present(alertView, animated: true, completion: nil)
       }
    
}
